package top.so.controller;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import top.so.dto.DraftsDTO;
import top.so.dto.UserDTO;
import top.so.service.DraftsService;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/drafts")
@SessionAttributes("isSuccess")//操作状态
public class DraftsController {
    @Autowired
    private DraftsService draftsService;
    /**
     * 文章存入草稿箱
     * @param draftsDTO
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "saveDrafts",method = RequestMethod.POST,produces="application/json")
    @ResponseBody
    public String saveDrafts(DraftsDTO draftsDTO, HttpSession httpSession){
        String result = null;
        Map<String,Object> map = new HashMap<String,Object>();
        ObjectMapper mapper = new ObjectMapper();
        //从session中获取当前用户，并且赋值给文章作者
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        draftsDTO.setUserID(userDTO.getUserID());
        if(draftsService.insertDrafts(draftsDTO)){
            map.put("isSuccess","true");
        }
        else{
            map.put("isSuccess","false");
        }

        try {
            result = mapper.writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @RequestMapping(value = "deleteDrafts",method = RequestMethod.POST)
    public ModelAndView deleteDrafts(DraftsDTO draftsDTO,ModelMap modelMap){
        ModelAndView mv = new ModelAndView("redirect:/myBlog/drafts");
        if(draftsService.deleteDrafts(draftsDTO)){
            modelMap.addAttribute("isSuccess","true");
        }
        else{
            modelMap.addAttribute("isSuccess","false");
        }
        return mv;
    }

    @RequestMapping(value = "goPage",method = RequestMethod.POST)
    public ModelAndView goPage(int pageNum,HttpSession httpSession){
        UserDTO userDTO = (UserDTO) httpSession.getAttribute("currUser");
        ModelAndView mv = new ModelAndView("user/Drafts");
        DraftsDTO draftsDTO = new DraftsDTO();
        draftsDTO.setUserID(userDTO.getUserID());
        List<DraftsDTO> draftsDTOList = draftsService.selectWithPage(draftsDTO,pageNum);
        mv.addObject("draftsDTOList",draftsDTOList);
        return mv;
    }

}
